<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable">
      <template #form-classifyId="{ model, field }">
        <a-cascader v-model:value="model[field]" :options="options" placeholder="请选择"
          :fieldNames="{ label: 'classifyName', value: 'classifyId' }" />
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">新增</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="[
            {
              label: '修改',
              onClick: handleEdit.bind(null, record),
            },

            {
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: handleDelete.bind(null, record.id),
              },
            },
          ]" />
        </template>
      </template>
    </BasicTable>
    <ModalAddRecord @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script setup
  lang="ts">
  import { PageWrapper } from '@/components/Page'
  import { BasicTable, useTable, TableAction } from '@/components/Table'
  import { searchFormSchema, columns } from './data'
  import { ref } from 'vue'
  import { useModal } from '@/components/Modal'
  import { message } from 'ant-design-vue'
  import ModalAddRecord from './ModalAddRecord.vue'

  import { getEnergyLibraryTableList, deleteEnergyLibraryRecord } from '@/api/energyCompare/energyLibrary'

  defineOptions({ name: 'EnergyLibrary' })
  const options = ref([])

  const [registerTable, { reload, updateTableDataRecord }] = useTable({
    title: '能效指标库',
    rowKey: 'id',
    api: getEnergyLibraryTableList,
    columns,
    useSearchForm: true,
    size: 'small',
    formConfig: {
      labelWidth: 80,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
    },
    bordered: false,
    striped: true,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
    },
  })
  const [registerModal, { openModal }] = useModal()

  const handleDelete = (id) => {
    deleteEnergyLibraryRecord({ id }).then((res) => {
      message.success('删除成功')
      reload()
    })
  }
  const handleEdit = (record) => {
    openModal(true, {
      record,
      isUpdate: true,
    })
  }
  const handleCreate = () => {
    openModal(true, {
      isUpdate: false,
    })
  }
  // 添加成功
  const handleSuccess = ({ isUpdate, values }) => {
    if (isUpdate) {
      // 演示不刷新表格直接更新内部数据。
      // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
      const result = updateTableDataRecord(values.id, values)
      console.log(result)
    } else {
      reload()
    }
  }
</script>
